package com.emasdemo.application;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.alibaba.ha.adapter.AliHaAdapter;
import com.alibaba.ha.adapter.AliHaConfig;
import com.alibaba.ha.adapter.Plugin;
import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.alibaba.sdk.android.httpdns.HttpDns;
import com.alibaba.sdk.android.httpdns.HttpDnsService;
import com.alibaba.sdk.android.httpdns.ILogger;
import com.alibaba.sdk.android.man.MANService;
import com.alibaba.sdk.android.man.MANServiceProvider;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.GcmRegister;
import com.alibaba.sdk.android.push.register.MeizuRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.emasdemo.R;
import com.emasdemo.util.LogUtils;

public class MainApplication extends Application {
    public static Application mApplication = null;

    @Override
    public void onCreate() {
        super.onCreate();

        mApplication = MainApplication.this;
//        SophixManager.getInstance().queryAndLoadNewPatch();//移动热修复拉取补丁
       
        initHa();//初始化崩溃分析
        initMan();//初始化数据分析
        initHttpDns();//初始化httpdns
		initCloudChannel(getApplicationContext());//初始化推送
        FeedbackAPI.init(this, SophixStubApplication.appkey, SophixStubApplication.appSecret);//初始化用户反馈
    }

    private void initHttpDns() {
        HttpDnsService httpdns = HttpDns.getService(getApplicationContext(), SophixStubApplication.httpdns_accountId, SophixStubApplication.httpdns_secretKey);
        //设置网络切换时是否自动刷新所有域名解析结果，如果打开此开关，在网络切换时，会自动刷新所有域名的解析结果，但会产生一定流量消耗
        httpdns.setPreResolveAfterNetworkChanged(true);
        httpdns.setLogEnabled(true);//设置是否httpdns输出日志
        httpdns.setExpiredIPEnabled(true);// 允许过期IP以实现懒加载策略
        httpdns.setCachedIPEnabled(true);//允许持久化缓存
        httpdns.enableIPv6(true);//开启ipv6功能

    }

    private void initHa() {
        //ha init
        AliHaAdapter.getInstance().openPublishEmasHa();

        AliHaConfig config = new AliHaConfig();
        config.appKey = SophixStubApplication.appkey;
        config.appVersion = "1.0";
        config.appSecret = SophixStubApplication.appSecret;
        config.channel = "EMAS";
        config.userNick = null;
        config.application = this;
        config.context = getApplicationContext();
        config.isAliyunos = false;
        config.rsaPublicKey = SophixStubApplication.rsaSecretHA;

        AliHaAdapter.getInstance().addPlugin(Plugin.crashreporter);    //崩溃分析，如不需要可注释掉
        AliHaAdapter.getInstance().addPlugin(Plugin.apm);              //性能监控，如不需要可注释掉
        AliHaAdapter.getInstance().addPlugin(Plugin.tlog);             //移动日志，如不需要可注释掉

        AliHaAdapter.getInstance().openDebug(true);          //调试日志开关

        AliHaAdapter.getInstance().start(config);                     //启动
    }

    private void initMan() {
        // 获取MAN服务
        MANService manService = MANServiceProvider.getService();
        // 打开调试日志，线上版本建议关闭
        manService.getMANAnalytics().turnOnDebug();
        // 若需要关闭 SDK 的自动异常捕获功能可进行如下操作(如需关闭crash report，建议在init方法调用前关闭crash),详见文档5.4
        manService.getMANAnalytics().turnOffCrashReporter();
        // 设置渠道（用以标记该app的分发渠道名称），如果不关心可以不设置即不调用该接口，渠道设置将影响控制台【渠道分析】栏目的报表展现。如果文档3.3章节更能满足您渠道配置的需求，就不要调用此方法，按照3.3进行配置即可；1.1.6版本及之后的版本，请在init方法之前调用此方法设置channel.
        manService.getMANAnalytics().setChannel("EMAS");
        // MAN初始化方法之一，从AndroidManifest.xml中获取appKey和appSecret初始化，若您采用上述 2.3中"统一接入的方式"，则使用当前init方法即可。
        manService.getMANAnalytics().init(this, getApplicationContext());

        // MAN另一初始化方法，手动指定appKey和appSecret
        // 若您采用上述2.3中"统一接入的方式"，则无需使用当前init方法。
        // String appKey = "******";
        // String appSecret = "******";
        // manService.getMANAnalytics().init(this, getApplicationContext(), appKey, appSecret);
        // 通过此接口关闭页面自动打点功能，详见文档4.2
//        manService.getMANAnalytics().turnOffAutoPageTrack();
        // 若AndroidManifest.xml 中的 android:versionName 不能满足需求，可在此指定
        // 若在上述两个地方均没有设置appversion，上报的字段默认为null
//        manService.getMANAnalytics().setAppVersion("1.0.0");
    }

    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        pushService = PushServiceFactory.getCloudPushService();
//        pushService.setPushIntentService(MyMessageIntentService.class);
//        pushService.setLogLevel(CloudPushService.LOG_OFF);//ogLevel 支持设置：CloudPushService.ERROR | CloudPushService.INFO | CloudPushService.DEBUG | CloudPushService.OFF（关闭Log）
        pushService.register(applicationContext, commonCallback);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id，对应服务端AndroidNotificationChannel参数，或者对应控制台Android 8.0特殊渠道参数
            String id = "8.0up";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "notification channel";
            // 用户可以看到的通知渠道的描述
            String description = "notification description";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            //下面是创建NotificationChannel，可自行设置NotificationChannel的各种属性，比如声音、震动等
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);// 配置通知渠道的属性
            mChannel.enableLights(true);// 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);// 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.setBypassDnd(true);//设置是否绕过免打扰模式
            mChannel.setSound(Uri.parse("android.resource://" + getPackageName()+"/" + R.raw.alicloud_notification_sound), Notification.AUDIO_ATTRIBUTES_DEFAULT);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道，可创建多个NotificationChannel，每次可选不同id进行实际通知使用
            mNotificationManager.createNotificationChannel(mChannel);
        }

        HuaWeiRegister.register(this); // 接入华为辅助推送
        MiPushRegister.register(applicationContext, "", ""); // 初始化小米辅助推送
        MeizuRegister.register(applicationContext, "", "");//接入魅族辅助推送
        OppoRegister.register(applicationContext, "", "");
        VivoRegister.register(applicationContext);//接入vivo辅助推送
        GcmRegister.register(applicationContext, "", ""); // 接入FCM/GCM初始化推送

    }

    /**
     * 获取当前进程名
     */
    private String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }

    private CloudPushService pushService;
    private CommonCallback commonCallback = new CommonCallback() {
        @Override
        public void onSuccess(String s) {
            Log.i("MPS:push---->", "init cloudchannel success" + "    deviceId    " + pushService.getDeviceId());
        }

        @Override
        public void onFailed(String errorCode, String errorMessage) {
            Log.i("MPS:push---->", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
        }
    };

    public static Context getApplication() {
        return mApplication;
    }
}
